package lch.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lch.dao.CheckUserDao;
import lch.entity.PageResult;
import lch.entity.QueryPageBean;
import lch.pojo.CheckGroup;
import lch.pojo.User;
import lch.service.CheckUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * @author Ber
 * @date 2020-01-16 18:59
 */
@Service(interfaceClass = CheckUserService.class)
@Transactional
public class CheckUserServiceImpl implements CheckUserService {
    @Autowired
    private CheckUserDao checkUserDao;

    @Override
    public List<User> findAll() {
        return checkUserDao.findAll();
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = checkUserDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        checkUserDao.add(user);
        Integer userId = user.getId();
        this.setUserAndCheckRole(userId,roleIds);
    }



    @Override
    public void edit(User user, Integer[] roleIds) {
        //编辑左侧
        checkUserDao.edit(user);
        //删除原先关联
        checkUserDao.deleteAssoication(user.getId());
        //重新建立关系
        this.setUserAndCheckRole(user.getId(),roleIds);
    }

    @Override
    public User findById(Integer id) {
        return checkUserDao.findById(id);
    }

    @Override
    public List<Integer> findCheckRoleIdsByCheckUserId(Integer id) {
        return checkUserDao.findCheckRoleIdsByCheckUserId(id);
    }

    @Override
    public void delete(Integer id) {
        long count = checkUserDao.findCountByCheckRoleId(id);

        checkUserDao.deleteUserIdAndRoleId(id);

        checkUserDao.deleteById(id);
    }
    private void setUserAndCheckRole( Integer userId,Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {//加个判断
            for (Integer roleId : roleIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("user_id", userId);
                map.put("role_id", roleId);
                checkUserDao.setUserAndCheckRole(map);
            }
        }
    }
}